package com.zhuiyun.project.security.commonhandler;

import com.zhuiyun.project.api.wxlogin.service.WxLoginService;

import com.zhuiyun.project.api.appuser.entity.User;
import com.zhuiyun.project.api.appuser.mapper.AppUserMapper;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.common.response.ResponseUtil;
import com.zhuiyun.project.security.jwt.JWTConfig;
import com.zhuiyun.project.security.jwt.JWTUtils;
import com.zhuiyun.project.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * @ClassName AuthenticationSuccessHandler
 * @Description 微信小程序登录成功的操作
 * @Author zcy
 * @Date 2023/3/27 11:20
 **/
@Component
public class WechatAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    AppUserMapper appUserMapper;
    @Autowired
    WxLoginService wxLoginService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String phone = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // 获取用户信息
        User user = wxLoginService.getUserByPhone(phone);
        String formattedBirthday = null; // 初始化格式化后的日期字符串为 null
        if (user.getUserBirthday() != null) {
            // 如果用户生日不为空，则格式化日期为字符串
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            formattedBirthday = dateFormat.format(user.getUserBirthday());
        }
        user.setUpdateTime(new Date());
        appUserMapper.updateByPrimaryKeySelective(user);
        String token = JWTUtils.createAccessToken(user, null);
        // 设置token过期时间
        RedisUtil.set(token, user, JWTConfig.expiration);
        RedisUtil.set(user.getUserPhone(), token, JWTConfig.expiration);
        token = JWTConfig.tokenPrefix + token;
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("imageId", user.getImageId());
        hashMap.put("token", token);
        hashMap.put("userId", user.getId());
        hashMap.put("userBirthday", formattedBirthday); // 使用格式化后的日期字符串
        hashMap.put("userType", user.getUserType());
        hashMap.put("userName", user.getUserName());
        hashMap.put("userPhone", user.getUserPhone());
        hashMap.put("friendNewNum", user.getFriendNewNum());
// 将token 放入redis中
        ResponseUtil.responseJson(response, CommonResult.ok(hashMap));
    }
}
